<template>
  <div class="purchase-order-list">
    <van-nav-bar
      title="采购订单"
      left-text="返回"
      left-arrow
      @click-left="router.back()"
    />
    
    <van-search
      v-model="searchQuery"
      placeholder="搜索采购订单"
      @search="handleSearch"
    />
    
    <van-dropdown-menu>
      <van-dropdown-item v-model="statusFilter" :options="statusOptions" @change="handleFilterChange" />
    </van-dropdown-menu>
    
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell
          v-for="order in orderList"
          :key="order.purchaseOrderId"
          :title="`订单 #${order.purchaseOrderId}`"
          :label="`供应商: ${order.name} | 金额: ¥${order.totalAmount}`"
          @click="viewOrderDetail(order.purchaseOrderId)"
        >
          <template #value>
            <van-tag :type="getStatusTagType(order.status)">
              {{ order.status }}
            </van-tag>
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
    
    <!-- 新增订单浮动按钮 -->
    <van-floating-bubble
      v-model:offset="offset"
      axis="xy"
      magnetic="x"
      @click="showCreateDialog = true"
    >
      <van-icon name="plus" size="24" />
    </van-floating-bubble>
    
    <!-- 新增订单对话框 -->
    <van-dialog
      v-model:show="showCreateDialog"
      title="新建采购订单"
      show-cancel-button
      @confirm="handleCreateOrder"
    >
      <van-form @submit="handleCreateOrder" class="create-form">
        <van-cell-group inset>
          <van-field
            v-model="newOrder.name"
            label="供应商名称"
            placeholder="请输入供应商名称"
            :rules="[{ required: true, message: '请填写供应商名称' }]"
          />
          <van-field
            v-model="newOrder.orderDate"
            label="订单日期"
            placeholder="请选择订单日期"
            readonly
            @click="showDatePicker = true"
            :rules="[{ required: true, message: '请选择订单日期' }]"
          />
          <van-field
            v-model="newOrder.totalAmount"
            label="总金额"
            placeholder="请输入总金额"
            type="number"
            :rules="[{ required: true, message: '请填写总金额' }]"
          />
        </van-cell-group>
      </van-form>
    </van-dialog>
    
    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { getPurchaseOrderList, createPurchaseOrder } from '@/api/purchaseOrder'
import { showSuccessToast, showFailToast } from 'vant'

const router = useRouter()
const orderList = ref([])
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)
const searchQuery = ref('')
const statusFilter = ref('')
const page = ref(1)
const pageSize = 10
const total = ref(0)
const showCreateDialog = ref(false)
const showDatePicker = ref(false)

// 新订单表单数据
const newOrder = ref({
  name: '',
  orderDate: '',
  totalAmount: ''
})

const statusOptions = [
  { text: '全部状态', value: '' },
  { text: '待审批', value: 'pending' },
  { text: '已批准', value: 'approved' },
  { text: '已拒绝', value: 'rejected' }
]

const offset = ref({ x: 200, y: 100 })

const getStatusTagType = (status) => {
  switch (status) {
    case 'approved': return 'success'
    case 'rejected': return 'danger'
    default: return 'primary'
  }
}

// 获取数据方法
const fetchData = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      page.value = 1
      refreshing.value = true
    } else {
      loading.value = true
    }
    
    const params = {
      page: page.value,
      pageSize,
      search: searchQuery.value,
      status: statusFilter.value
    }
    
    const { data } = await getPurchaseOrderList(params)
    
    if (isRefresh) {
      orderList.value = data.list
    } else {
      orderList.value = [...orderList.value, ...data.list]
    }
    
    total.value = data.total || 0
    finished.value = orderList.value.length >= total.value
    
    if (!isRefresh && data.list.length > 0) {
      page.value += 1
    }
  } catch (error) {
    console.error('获取采购订单列表失败:', error)
    showFailToast('获取数据失败')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 日期选择确认
const onDateConfirm = ({ selectedValues }) => {
  newOrder.value.orderDate = selectedValues.join('-')
  showDatePicker.value = false
}

// 创建新订单
const handleCreateOrder = async () => {
  try {
    loading.value = true
    const response = await createPurchaseOrder(newOrder.value)
    
    showSuccessToast('创建成功')
    showCreateDialog.value = false
    
    // 重置表单
    newOrder.value = {
      name: '',
      orderDate: '',
      totalAmount: ''
    }
    
    // 刷新列表
    fetchData(true)
  } catch (error) {
    console.error('创建订单失败:', error)
    showFailToast('创建失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  orderList.value = []
  finished.value = false
  fetchData(true)
}

// 筛选处理
const handleFilterChange = () => {
  orderList.value = []
  finished.value = false
  fetchData(true)
}

// 下拉刷新
const onRefresh = () => {
  fetchData(true)
}

// 滚动加载
const onLoad = () => {
  if (!finished.value) {
    fetchData()
  }
}

// 初始化加载
fetchData(true)

const viewOrderDetail = (id) => {
  router.push({ name: 'PurchaseOrderDetail', params: { id } })
}
</script>

<style scoped>
.purchase-order-list {
  padding-bottom: 50px;
}

.create-form {
  padding: 16px;
}
</style>